import {
  Table,
  Form,
  message,
  DatePicker,
  Input,
  Button,
  Image,
  Modal,
  Upload,
  Space,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
  EyeOutlined,
  SearchOutlined,
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
} from '@ant-design/icons';
import { FC, ReactNode, useEffect, useState, useRef } from 'react';
import type { RcFile, UploadProps, UploadChangeParam } from 'antd/es/upload';
import type { UploadFile } from 'antd/es/upload/interface';
import * as api from '@/api/product';
import ModalCom from '@/components/modalBase';
import './index.css';

type DataType = {
  categoryImgurl?: string;
  category_id: string;
  categoryName: string;
  creator: string;
  createTime: string;
  updateTime?: string;
  updator?: string;
};

declare global {
  interface productParam {
    product_id?: string;
    category_id?: string;
    categoryName?: string;
    categoryImgurl?: string;
    productName?: string;
    price?: number;
    description?: string;
    inventory?: number;
    imageUrl?: string;
  }
}

const ProductCategory = () => {
  // 表格数据
  let [data, setData] = useState<DataType[]>([]);
  // 模态框是否显示的属性
  const [isModalOpen, setIsModalOpen] = useState(false);

  //  表单中类目名称
  const [name, setName] = useState<string>('');
  // 对话框的标题
  const [title, setTitle] = useState<string>('');
  // 修改的时候的类目id
  const [category_id, setCategoryId] = useState<string>('');
  // 删除时打开的模态框
  const [ModalOpen, setModalOpen] = useState<boolean>(false);
  // 存储删除时的product_id
  const [delId, setDelId] = useState<string>('');

  // 拿到子组件暴露来的属性
  let fff = useRef<any>(null);

  // 请求数据
  let getCategory = async () => {
    let res = await api.getCategory();
    // console.log(res)
    setData(res.data.data);
    res.data.data.forEach((item: any) => {
      item.key = Math.random().toString(32).substring(2);
    });
  };

  useEffect(() => {
    // 调用请求方法
    // console.log(aaa,"jkfjdsgfjgfjsgdfj");

    getCategory();
  }, []);

  // 注册表头数据
  let columns: ColumnsType<DataType> = [
    {
      title: '类目图片',
      dataIndex: 'categoryImgurl',
      align: 'center',
      render(row) {
        return (
          <Image
            // width={200}
            src={
              row
                ? row
                : 'https://img2.baidu.com/it/u=2421090168,324781765&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1673110800&t=25e086e66b814c4966b8ae843e6586c6'
            }
          />
        );
      },
    },
    {
      title: '类目id',
      dataIndex: 'category_id',
      align: 'center',
    },
    {
      title: '类目名称',
      dataIndex: 'categoryName',
      align: 'center',
    },
    {
      title: '类目创建者',
      dataIndex: 'creator',
      align: 'center',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      align: 'center',
      defaultSortOrder: 'descend',
      sorter: (a, b) => {
        let date1 = new Date(Date.parse(a.createTime.replace(/-/g, '/'))); //转换为Dat()
        let date2 = new Date(Date.parse(b.createTime.replace(/-/g, '/'))); //转换为Dat()
        return date1.getTime() - date2.getTime();
      },
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      align: 'center',
    },
    {
      title: '更新者',
      dataIndex: 'updator',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      align: 'center',
      render(row, record) {
        // console.log(row)
        return (
          <div className="action_button">
            <Button
              type="primary"
              icon={<EyeOutlined />}
              style={{ backgroundColor: '#32CD32', borderColor: '#32CD32' }}
            />
            <Button
              type="primary"
              icon={<EditOutlined />}
              onClick={updateCategory(row, record)}
            />
            <Button
              type="primary"
              icon={<DeleteOutlined />}
              danger
              onClick={delCategory(row, record)}
            />
          </div>
        );
      },
    },
  ];

  // 按钮控制模态框显示
  const showModal = () => {
    setIsModalOpen(true);
    setTitle('添加类目');
  };

  // 删除类目
  let delCategory = (row: any, record: any) => async () => {
    setModalOpen(true);
    // console.log(record.category_id)
    setDelId(record.category_id);
  };

  // 删除打开的模态框
  // 确定按钮
  const handleOkk = async () => {
    try {
      let res = await api.delCategory(delId);
      if (res.data.state) {
        // 更新列表
        getCategory();
        // 关闭模态框
        setModalOpen(false);
        // 删除成功提示
        message.open({
          type: 'success',
          content: '删除成功',
        });
      }
    } catch (e) {
      // 删除失败提示
      message.open({
        type: 'error',
        content: '删除失败',
      });
    }
  };
  // 取消按钮
  const handleCancell = () => {
    // 关闭模态框
    setModalOpen(false);
    // 取消删除提示框
    message.open({
      type: 'warning',
      content: '已取消删除',
    });
  };

  // 修改类目
  let updateCategory = (row: any, record: any) => async () => {
    setIsModalOpen(true);
    // 修改标题
    setTitle('修改类目');
    // console.log(record)
    // 回显数据到对话框上
    fff.current.bb('categoryName', record.categoryName);
    // 回显图片
    fff.current.aa(record.categoryImgurl);

    setCategoryId(record.category_id);
  };

  //
  let handleChange = (pagination: any) => {
    console.log(pagination);
  };

  return (
    <>
      <Space>
        <div>
          <div className="operation">
            <div className="button">
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={showModal}
              >
                添加类目
              </Button>
              <Button type="primary" icon={<DeleteOutlined />} danger>
                批量删除
              </Button>
            </div>
            <Modal
              title="删除提示"
              open={ModalOpen}
              okText="确定"
              cancelText="取消"
              onOk={handleOkk}
              onCancel={handleCancell}
            >
              <p>确定删除这条数据吗？</p>
            </Modal>
            <div className="search">
              <Form
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 14 }}
                initialValues={{ remember: true }}
              >
                <Form.Item label="商品内容">
                  <Input />
                </Form.Item>
                <Form.Item label="添加时间">
                  <DatePicker />
                </Form.Item>
              </Form>
              <Button type="primary" icon={<SearchOutlined />}>
                查询
              </Button>
            </div>
          </div>
          <Table
            dataSource={data}
            columns={columns}
            scroll={{ x: 500, y: 360 }}
            onChange={handleChange}
            pagination={{ position: ['bottomLeft'], pageSize: 10 }}
          />
          <ModalCom
            ref={fff}
            title={title}
            category_id={category_id}
            isModalOpen={isModalOpen}
            getCategory={getCategory}
            setIsModalOpen={setIsModalOpen}
          ></ModalCom>
        </div>
      </Space>
    </>
  );
};

export default ProductCategory;
